package com.campus.system.controller.admin;

import com.campus.common.domain.LoginUser;
import com.campus.common.domain.User;
import com.campus.common.dto.ResponseDto;
import com.campus.common.dto.UserDto;
import com.campus.common.service.LoginUserService;
import com.campus.common.service.UserService;
import com.campus.common.utils.JwtUtil;
import com.campus.common.utils.ValidatorUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private LoginUserService loginUserService;
    @Resource
    private UserService userService;
    @RequestMapping("/test")
    public String test() {
        return "test";
    }
    @RequestMapping("/login")
    public ResponseDto login(@RequestBody UserDto userDto) {
        ResponseDto responseDto = new ResponseDto();

        // 校验登录账号密码
        ValidatorUtil.require(userDto.getAccount(), "账号");
        ValidatorUtil.require(userDto.getPassword(), "密码");
        userDto.setUsername(userDto.getAccount());
        // TODO 应当判断输入的账号是邮箱还是用户名

        // 通过用户名登录
        LoginUser loginUser = loginUserService.loginByUsername(userDto);
        if (loginUser != null) {
            userDto = loginUser.getUserDto();
            log.info("-----------------" + userDto.getUserId());
            userDto.setToken(JwtUtil.createJWT(String.valueOf(userDto.getUserId())));
            // 将密码设置为空
            userDto.setPassword("");
            responseDto.setContent(loginUser.getUserDto());
        }
        return responseDto;
    }
    @RequestMapping("/register")
    public ResponseDto register(@RequestBody UserDto userDto) {
        ResponseDto responseDto = new ResponseDto();
        // 密码不能为空
        ValidatorUtil.require(userDto.getPassword(), "密码");
        ValidatorUtil.require(String.valueOf(userDto.getVerifyCode()), "验证码");
        ValidatorUtil.length(String.valueOf(userDto.getVerifyCode()), "验证码", 6, 6);
        // 优先邮箱注册
        if(userDto.getEmail() != null) {
            ValidatorUtil.containStr(userDto.getEmail(), "@", "邮箱");
            userService.registerByEmail(userDto);
        } else  {
            ValidatorUtil.require(userDto.getPhoneNumber(), "手机号");
            userService.registerByPhoneNumber(userDto);
        }
        // 校验登录账号密码
        ValidatorUtil.require(userDto.getUsername(), "用户名");
        ValidatorUtil.unContainStr(userDto.getUsername(),"@", "用户名");
        ValidatorUtil.require(userDto.getPassword(), "密码");
        ValidatorUtil.require(userDto.getEmail(), "邮箱");

        return responseDto;
    }
}
